package ca.etsmtl.log730.projet2.connectors.clientserver.setup;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;

import ca.etsmtl.log730.projet2.connectors.clientserver.LinkFactory;

public class LocalServerData extends ConnectionData {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3332684135237799854L;

	public LocalServerData() {
		this(12345);
	}
	public LocalServerData(int p) {
		super(getStaticHostname(), p);
	}

	public static LocalServerData loadLocalServerData() {
		LocalServerData lsd = null;
		 try{
		      //use buffering
		      InputStream file = new FileInputStream( "server.data" );
		      InputStream buffer = new BufferedInputStream( file );
		      ObjectInput input = new ObjectInputStream ( buffer );
		      try{
		    	  lsd = (LocalServerData) input.readObject();
		      } catch(Exception e) {
		    	  
		      } finally{
		        input.close();
		      }
		} catch(Exception e) {
//			e.printStackTrace();
		} 
		 return lsd;
	}
	public static String getStaticHostname() {
		String s = "127.0.0.1";
		try{
			InetAddress ip=InetAddress.getLocalHost();
			s = ip.getHostAddress();
		} catch (Exception e){
			e.printStackTrace(); 
		}
		return s;
	}
	public static LocalServerData getLocalServerMain() {
		LocalServerData lsd = null;
		 
		if(lsd == null || !LinkFactory.available(lsd.getPort())) {
			
			int p = LinkFactory.finNextAvailable(1245);
			lsd = new LocalServerData(p);
			
		}
		try{
			InetAddress ip=InetAddress.getLocalHost();
			lsd.setHostname(ip.getHostAddress());
		} catch (Exception e){
			e.printStackTrace(); 
		}
	
	    try{
	        //use buffering
	        OutputStream file = new FileOutputStream( "server.data" );
	        OutputStream buffer = new BufferedOutputStream( file );
	        ObjectOutput output = new ObjectOutputStream( buffer );
	        try{
	          output.writeObject(lsd);
	        }
	        finally{
	          output.close();
	        }
	      } catch(Exception e) {
				e.printStackTrace();
			} 
		
		return lsd;
	}
}
